package cn.ymatrix.deleteDataFromYMatrix;

import cn.ymatrix.logger.LoggerLevel;
import cn.ymatrix.logger.MxLogger;
import cn.ymatrix.utils.Config;
import cn.ymatrix.utils.DataUtil;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.TimeUnit;

public class DeleteBatchFromYMatrix {

  public static void main(String[] args) {

    MxLogger.loggerLevel(LoggerLevel.INFO);
    Logger LOGGER = MxLogger.init(DeleteBatchFromYMatrix.class);

    Connection connection = null;
    String tableName = Config.getTableName();
    int batchSize = Config.getBatchSize();
    int totalNumber = Config.getTotalNumber();
    Statement statement = null;
    int insertCount = 0;
    int counter = 0;

    try {
      connection = Config.getDateSource().getConnection();
      statement = connection.createStatement();
      LOGGER.info("---- 开始删除数据 ----");
      StopWatch startWatch = StopWatch.createStarted();

      for (counter = 1; counter <= totalNumber; counter++) {
        if (counter % batchSize == 0) {
          insertCount++;
          String deleteSql = getUpdateSQL(batchSize, tableName);
          statement.executeUpdate(deleteSql);
          LOGGER.info("成功删除第 " + counter + " 条数据");
        }
      }

      int tailCount = totalNumber - insertCount * batchSize;
      if (tailCount != 0) {
        String deleteSql = getUpdateSQL(tailCount, tableName);
        statement.executeUpdate(deleteSql);
      }

      LOGGER.info(
          "成功删除 " + totalNumber + " 条数据,耗时: " + startWatch.getTime(TimeUnit.MILLISECONDS) + "毫秒");

    } catch (SQLException e) {
      e.printStackTrace();
      try {
        connection.rollback();
      } catch (SQLException ex) {
        ex.printStackTrace();
      }
    } finally {
      try {
        connection.close();
        statement.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }

  private static String getUpdateSQL(int batchSize, String tableName) {
    StringBuilder deleteSql = new StringBuilder("BEGIN; ");
    for (int i = 1; i <= batchSize; i++) {
      deleteSql.append(
          "delete from  "
              + tableName
              + " where vin = "
              + DataUtil.getIntValue()
              + " and t1 = "
              + DataUtil.getIntValue()
              + " ;");
    }
    return deleteSql.append("COMMIT;").toString();
  }
}
